package xjay.ai.emotionalsupport.agent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import xjay.ai.emotionalsupport.chatmemory.ChatHistoryService;
import xjay.ai.emotionalsupport.rag.RagService;
import xjay.ai.emotionalsupport.tools.Markdown2TextTool;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class MaidAgent extends CharacterBaseAgent{



    public MaidAgent(
            @Qualifier("maidAgentTools") ToolCallback[] maidAgentTools,
            ChatModel qwenChatModel,
//            @Qualifier("tarotRag")
//            RagService ragService,
            ChatHistoryService chatHistoryService,
            Markdown2TextTool markdown2TextTool,
            AgentPromptConfig agentPromptConfig) throws IOException {



        //加载工具调用
        super(maidAgentTools);

        super.setAgentName("MaidAgent");
        //加载三份提示词
        String SYSTEM_PROMPT = agentPromptConfig.loadAgentPrompt("maid_system_prompt.md");
        String INSTRUCTION_PROMPT = agentPromptConfig.loadAgentPrompt("maid_instruction_prompt.md");
        String FINAL_PROMPT = agentPromptConfig.loadAgentPrompt("maid_final_prompt.md");
        super.setSystemPrompt(SYSTEM_PROMPT);
        super.setInstructionPrompt(INSTRUCTION_PROMPT);
        super.setFinalPrompt(FINAL_PROMPT);

        //设置AgentLoop循环最大步数
        super.setMaxStep(5);

        //设置历史对话处理器
        super.setChatHistoryService(chatHistoryService);

        //设置输出过滤器
        super.setMarkdown2TextTool(markdown2TextTool);

        //不设置rag了

        //设置chatClient
        ChatClient chatClient = ChatClient.builder(qwenChatModel).build();
        super.setChatClient(chatClient);

    }

    /**
     * note: 冷启动
     * @param userId
     * @param sessionId
     */
    public void warmUp(String userId, String sessionId) {

        log.info("maidAgent: 冷启动");
        List<Message> historyMessages= super.getChatHistoryService().contextMessages(userId, sessionId);
        if(!historyMessages.isEmpty()){

            // 1) 生成用户画像摘要
            //String userProfile = tarotUserProfileService.generateUserProfile(userId, sessionId);

            // 2) 将画像并入系统提示词，使角色设定天然具备用户记忆
//            String enrichedSystemPrompt = getSystemPrompt() + "\n\n【用户画像摘要】\n" + userProfile;
//            setSystemPrompt(enrichedSystemPrompt);

            //log.info("在systemPrompt中注入用户信息摘要：{}", userProfile);
        }

    }

    public String maidChat(String userMessage, String userId, String sessionId) {


        String results = super.run(userMessage);

        Prompt prompt = new Prompt(getMessageList(), this.getChatOptions());

        log.info("maidAgent: 开始回复");

        // STEP:使用SYSTEM_PROMPT + FINAL_PROMPT,将内部分析结果转换为微信聊天风格的回复
        String assistantReply = getChatClient().prompt(prompt)
                .system(getSystemPrompt() + "\n\n" + getFinalPrompt())
                .user(userMessage)
                .call()
                .content();

        if(assistantReply == null || assistantReply.isEmpty()){
            log.error("maidAgent 回复为空？");
        }
        String reply = super.getMarkdown2TextTool().markdownToText(assistantReply);
        String preview = reply != null && reply.length() > 5 ? reply.substring(0, 5) : reply;
        log.info("tarotAgent: 回复结束，内容为 {} (长度: {})", preview, reply != null ? reply.length() : 0);

        //STEP:数据库持久化，插入一问一答
        super.getChatHistoryService().insertQA(userId, sessionId, userMessage, reply);

        return reply;
    }
}
